rm(list=ls())

wd <- ".../Replication/"
setwd(wd)

# Load/install packages ------------------------------------
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
  foreign, 
  ggplot2, 
  estimatr,
  texreg,
  xtable,
  fastDummies,
  sandwich,
  dplyr,
  janitor, 
  gridExtra,
  gsheet,
  zoo,
  interflex,
  lubridate,
  tidyverse,
  stringi,
  readxl,
  ri2,
  modelsummary,
  readxl, 
  haven,
  grid,
  ggpubr,
  Rmisc
)

options(scipen=999)

# Note: given the random component inherent to the randomization tests performed
# by ri(), you may observe small differences in the p-values of the randomization
# tests performed using that function.

# load database
data<-read.csv("Data/full police records 1827-1830.csv")

# clean 
data$date_month <- as.Date(data$date_month)
data$date_month <- format(data$date_month, "%m-%d")

data$nro_presos[is.na(data$nro_presos)] <- 0
data$nro_presos_esclavos[is.na(data$nro_presos_esclavos)] <- 0
data$nro_presos_negroslibres[is.na(data$nro_presos_negroslibres)] <- 0
data$nro_presos_negros <- data$nro_presos_negroslibres + data$nro_presos_esclavos

# keep only those imprisoned
data <-  data %>% filter(preso==1)
head(data)

# summarize
dd <- data %>% 
  dplyr::group_by(date) %>% 
  dplyr::summarise(
    `All Imprisoned` = sum(nro_presos),
    `Slaves Imprisoned` = sum(nro_presos_esclavos), 
    `Free Blacks Imprisoned` = sum(nro_presos_negroslibres)
  ) %>%
  pivot_longer(cols = `All Imprisoned`:`Free Blacks Imprisoned`,
               names_to = "variable",
               values_to = "Total Number Imprisoned")

dd$date <- as.Date(dd$date)

lim_dates <- c("1826-12-15", "1827-02-15", 
               "1827-11-15", "1828-02-15",
               "1828-11-15", "1829-02-15",
               "1829-11-15", "1830-02-15",
               "1830-11-15", "1830-12-31")
lim_dates <- as.Date(lim_dates)


Figure_A<-ggplot(dd, aes(x=date, y = `Total Number Imprisoned`)) +
  geom_rect(
    xmin = lim_dates[1], xmax = lim_dates[2],
    ymin = -Inf, ymax = Inf,
    fill = "grey80", alpha = 0.1
  ) + 
  geom_rect(
    xmin = lim_dates[3], xmax = lim_dates[4],
    ymin = -Inf, ymax = Inf,
    fill = "grey80", alpha = 0.1
  ) + 
  geom_rect(
    xmin = lim_dates[5], xmax = lim_dates[6],
    ymin = -Inf, ymax = Inf,
    fill = "grey80", alpha = 0.1
  ) + 
  geom_rect(
    xmin = lim_dates[7], xmax = lim_dates[8],
    ymin = -Inf, ymax = Inf,
    fill = "grey80", alpha = 0.1
  ) + 
  geom_rect(
    xmin = lim_dates[9], xmax = lim_dates[10],
    ymin = -Inf, ymax = Inf,
    fill = "grey80", alpha = 0.1
  ) + 
  geom_point() + geom_line() + 
  facet_wrap(~ variable, scales = "free_y", ncol =1) +
  theme_minimal() + 
  theme(legend.position = "none", 
        strip.text = element_text(size = 13),
        panel.spacing = unit(1, "cm"))


pdf("Output/FigureA6.pdf",height=8, width=10)
Figure_A
dev.off()


